package com.zxy.springboot_vue.controller;


import com.zxy.springboot_vue.config.AjaxResult;
import com.zxy.springboot_vue.entity.Menu;
import com.zxy.springboot_vue.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lenovo
 * @since 2021-10-19
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    /*查询所有的菜单*/
    @GetMapping("selectAll")
    public AjaxResult selectAll(){
        List<Menu> list = menuService.selectAll(0);
        return AjaxResult.ok(list);
    }

    @RequestMapping("findMenuByUid")
    public List<Menu> findMenuByUid(Integer uid){
        //根据用户id查询一级菜单
        List<Menu> oneL = menuService.findMenusByUid(uid,1);
        System.out.println("^^^^^"+oneL);
        return selectChild(uid,oneL);
    }

    private List<Menu> selectChild(Integer uid,List<Menu> oneL){
        ArrayList<Menu> oneList = new ArrayList<>();

        //遍历一级菜单
        if(oneL!=null && oneL.size()>0){
            oneL.forEach(oneMenu ->{
                System.out.println(oneMenu.getName()+"****");
                //根据一级的id作为二级的parentId查询二级菜单
                List<Menu> twoL = menuService.findMenusByUid(uid, oneMenu.getId());
                //多个角色有相同的二级菜单去重
                twoL = twoL.stream().distinct().collect(Collectors.toList());
                if(twoL!=null&&twoL.size()>0){
                    oneMenu.setChildren(twoL);
                    //递归调用
                    selectChild(uid,twoL);

                }
                oneList.add(oneMenu);
            });
        }
        //去重  多个角色有相同的一级菜单去重
        List<Menu> collect = oneList.stream().distinct().collect(Collectors.toList());
        return collect;

    }

}
